//
//  GDBusinessViewController.m
//  美团试验 (自己)
//
//  Created by 热带雨林 on 17/2/12.
//  Copyright © 2017年 热带雨林. All rights reserved.
//

#import "GDBusinessViewController.h"
#import "Masonry.h"
#import "GDFoodModel.h"
#import "CZAdditions.h"
#import "GDLeftCell.h"
#import "GDRightCell.h"
#import "GDHeaderView.h"
#import "GDBuyCar.h"
#import "GDBuyCarListController.h"
#import "GDBuyCarLL.h"
#import "GDBuyCarListLLController.h"
#import "GDDetailsViewController.h"
#import "GDPageController.h"


static NSString *ID = @"cellID";
static NSString *headID = @"headID";

@interface GDBusinessViewController ()<UITableViewDelegate,UITableViewDataSource,GDRightCellDelegate,CAAnimationDelegate,GDBuyCarLLDelegate>

@property(nonatomic, weak)UITableView *leftTable;
@property(nonatomic, weak)UITableView *rightTable;
@property(nonatomic, weak)GDBuyCarLL *buyCarLL;

@end

@implementation GDBusinessViewController{
    //所有商品的数组
    NSMutableArray <GDFoodModel *>*_dataArray;
    NSMutableArray <GDDetailsFoodModel *>*_selectedDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadData];
    
    _selectedDataArray = [NSMutableArray array];
    
    //创建一个通知，开始接收从详情页发送的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addData:) name:@"kNoticatioPageVBuyCar" object:nil];
    
}
- (void)setupUI{
    //创建左右两个tableView
    UITableView *leftTable = [[UITableView alloc]init];
    self.leftTable = leftTable;
    _leftTable.delegate = self;
    _leftTable.dataSource = self;
    
    [_leftTable registerClass:[GDLeftCell class] forCellReuseIdentifier:ID];
    
    _leftTable.rowHeight = 55;
    
    _leftTable.separatorStyle = UITableViewCellSelectionStyleNone;

    [self.view addSubview:leftTable];
    
    UITableView *rightTable = [[UITableView alloc]init];
    self.rightTable = rightTable;
    _rightTable.delegate = self;
    _rightTable.dataSource = self;
    
    [_rightTable registerClass:[GDRightCell class] forCellReuseIdentifier:ID];
    
    [_rightTable registerClass:[GDHeaderView class] forHeaderFooterViewReuseIdentifier:headID];
    
    //必须要给个高度
    _rightTable.sectionHeaderHeight = 23;
//    _rightTable.rowHeight = 105;
    
    //设置一下预估行高
    _rightTable.estimatedRowHeight = 105;
    _rightTable.rowHeight = UITableViewAutomaticDimension;
    _rightTable.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
    
    //取消下划线
//    _rightTable.separatorStyle = UITableViewCellSelectionStyleNone;
    
    [self.view addSubview:rightTable];
    
//    UIView *buyCarView = [[UIView alloc]init];
//    buyCarView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:buyCarView];
    
    //添加购物车
//    GDBuyCar *buyCarView = [GDBuyCar buyCarinit];
//    self.buyCar = buyCarView;
//    self.buyCar.delegate = self;
//    [self.view addSubview:buyCarView];
    
    GDBuyCarLL *buyCarView = [[GDBuyCarLL alloc]init];
    self.buyCarLL = buyCarView;
    buyCarView.delegate = self;
    [self.view addSubview:buyCarView];
    
    [leftTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.view);
        make.width.mas_equalTo(100);
    }];
    
    [rightTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(self.view);
        make.left.equalTo(leftTable.mas_right).offset(5);
//        make.bottom.equalTo(buyCarView.mas_top);
    }];
    
    [buyCarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(46);
    }];
}

- (void)loadData{
    
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"food.json" withExtension:nil];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    //解析数据，将data类型数据转换成NSDictionary
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    NSArray *array = dic[@"data"][@"food_spu_tags"];
    
    _dataArray = [NSMutableArray array];
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *dic , NSUInteger idx, BOOL * _Nonnull stop) {
        GDFoodModel *model = [GDFoodModel cz_objectWithDict:dic];
        
        [_dataArray addObject:model];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(tableView == _leftTable){
        return 1;
    }
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:  (NSInteger)section{

    if(tableView == _leftTable){
        return _dataArray.count;
    }
    return _dataArray[section].spus.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    //因为有两个cell，需要在此处进行一下判断
    if(tableView == _leftTable){
        cell.textLabel.text = _dataArray[indexPath.row].name;
    }else{
        
        ((GDRightCell *)cell).model = _dataArray[indexPath.section].spus[indexPath.row];
        
        //有个难点，就是指定rightCell的代理
        ((GDRightCell *)cell).delegate = self;
        
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(tableView == _leftTable){
        
        return nil;
    
    }
    
    GDHeaderView *headerV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    
    headerV.label.text = _dataArray[section].name;
    
    return headerV;
}
//两个tableView进行关联
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if(tableView == _leftTable){
        NSIndexPath *selectedPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        
        //点左 右边滚动
        [_rightTable scrollToRowAtIndexPath:selectedPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        return ;
    }
    GDPageController *pageV = [[GDPageController alloc]init];
    
    pageV.selectedIndexPath = indexPath;
    //传递了当前的indexPath 和选中的数据
    pageV.foodArray = _dataArray;
    pageV.selectedArray = _selectedDataArray;
    
    
    [self.navigationController pushViewController:pageV animated:YES];

    //失败
//    else if(tableView == _rightTable){
//    
//        NSIndexPath *selecPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
//        [_leftTable scrollToRowAtIndexPath:selecPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//        return ;
//    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _leftTable){
        return ;
    }
    NSIndexPath *selectedPath = [NSIndexPath indexPathForRow:indexPath.section inSection:0];

    //方法错了
//    [_rightTable scrollToRowAtIndexPath:selectedPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    //点右 左边滚动
    [_leftTable selectRowAtIndexPath:selectedPath animated:NO scrollPosition:UITableViewScrollPositionTop];
    
}
//实现rightCell的代理，将数据添加的DetailsModel 传到 控制器中
-(void)rightCell:(GDRightCell *)rigthCell withPlusModel:(GDDetailsFoodModel *)model withStartP:(CGPoint)startPoint{

    //开始使用动画
    [self animatedWithPoint:startPoint];
    
    if(![_selectedDataArray containsObject:model]){
        
        [_selectedDataArray addObject:model];
    }
}

- (void)animatedWithPoint:(CGPoint)startPoint{
    UIImageView *redView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_food_count_bg"]];
    redView.center = startPoint;
    UIWindow *keyWindow =[UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:redView];
    //开始使用关键帧动画
    CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //使用杯赛尔曲线
    UIBezierPath *path = [UIBezierPath bezierPath];
    //起点
    [path moveToPoint:startPoint];
    //自定义一个最高点
    CGPoint controlP = CGPointMake( startPoint.x- 150, startPoint.y - 200);
    //终点
    CGPoint endP = CGPointMake(50, [UIScreen mainScreen].bounds.size.height- 46);
    //设置路径
    [path addQuadCurveToPoint:endP controlPoint:controlP];
    //将路径赋值给动画
    keyAnima.path = path.CGPath;
    //动画的时长
    keyAnima.duration = 1;
    keyAnima.delegate = self;
    //标记小红点 方便以后取出删除
    [keyAnima setValue:redView forKey:@"red"];
    
    //将动画添加到小红点上
    //动画是添加在layer 上的
    [redView.layer addAnimation:keyAnima forKey:@"red"];
    //动画结束之后将小红点进行删除
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //由之前的记录将小红点取出，删除
    UIImageView *redImage = (UIImageView *)[anim valueForKey:@"red"];
    //将小红点进行删除
    [redImage removeFromSuperview];

//    self.buyCarLL.buyListModel = _selectedDataArray;
    self.buyCarLL.buyList = _selectedDataArray;

}

//减少的model

- (void)rigthCell:(GDRightCell *)rigthCell withMinusModel:(GDDetailsFoodModel *)model{
    
    if(model.buyCount == 0){
        [_selectedDataArray removeObject:model];
    }
//    self.buyCarLL.buyListModel = _selectedDataArray;
    self.buyCarLL.buyList = _selectedDataArray;
    
}

- (void)GDBuyCarController:(GDBuyCarLL *)buyCarVC withSelectedArray:(NSArray<GDDetailsFoodModel *> *)selectedArray{
    

    GDBuyCarListLLController *buyListC = [[GDBuyCarListLLController alloc]init];
    //使用madel
    //控制器弹出控制器
    [self presentViewController:buyListC animated:YES completion:nil];
    
}

- (void)addData:(NSNotification *)infor{

    //拿到从详情页穿过来的数据
    NSDictionary *dic = infor.userInfo;

    //还原数据
    GDDetailsFoodModel *model = dic[@"model"];
    
    model.buyCount ++;
    
    if(![_selectedDataArray containsObject:model]){
        
        [_selectedDataArray  addObject:model];
    }
    
    //
    _buyCarLL.buyList = _selectedDataArray;
    
    //跟新数据
    [_rightTable reloadData];
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
